/**
 * Copyright 2012 Pablo Danilo Aliscioni
 *
 *   Licensed under the Apache License, Version 2.0 (the "License");
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 */

package ar.com.pabloaliscioni.cloud.core.storage.providers.local;

import java.io.File;
import java.io.FilenameFilter;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

import ar.com.pabloaliscioni.cloud.api.exceptions.ConfigurationException;
import ar.com.pabloaliscioni.cloud.api.exceptions.ServiceException;
import ar.com.pabloaliscioni.cloud.core.configuration.ProviderConfiguration;
import ar.com.pabloaliscioni.cloud.core.storage.BaseStorageClient;

/**
 * Implementation of the IStorageClient interface for Local Storage service
 * 
 * @author Pablo Danilo Aliscioni
 * @since 1.0
 */
public class LocalStorageClient extends BaseStorageClient
{
	private String baseDirectory;

	@Override
	public void configure(ProviderConfiguration providerConfiguration)
	{
		try
		{
			this.setProviderName(providerConfiguration.getName());
			
			baseDirectory = providerConfiguration.getConfigurationValue("Local-Directory");
			
			if(!baseDirectory.endsWith("\\"))
				baseDirectory += "\\";
		}
		catch (Exception e)
		{
			throw new ConfigurationException(e);
		}
	}
	
	// API Implementation
	
	@Override
	public boolean containerExists(String containerName)
	{
		if(!isValidContainerName(containerName))
			throw new IllegalArgumentException("Invalid container name");
		
		try
		{
			Path path = Paths.get(baseDirectory + containerName);
			return Files.exists(path);
		}
		catch (Exception e)
		{
			throw new ServiceException(e);
		}
	}
	
	@Override
	public void createContainer(String containerName)
	{
		if(!isValidContainerName(containerName))
			throw new IllegalArgumentException("Invalid container name");
		
		try
		{
			Path path = Paths.get(baseDirectory + containerName);
			Files.createDirectory(path);
		}
		catch (Exception e)
		{
			throw new ServiceException(e);
		}
	}
	
	@Override
	public void deleteContainer(String containerName)
	{
		if(!isValidContainerName(containerName))
			throw new IllegalArgumentException("Invalid container name");
		
		try
		{
			Path path = Paths.get(baseDirectory + containerName);
			Files.delete(path);
		}
		catch (Exception e)
		{
			throw new ServiceException(e);
		}
	}
	
	@Override
	public void deleteFile(String containerName, String fileName)
	{
		if(!isValidContainerName(containerName))
			throw new IllegalArgumentException("Invalid container name");
		
		if(!isValidFileName(fileName))
			throw new IllegalArgumentException("Invalid file name");
		
		try
		{
			Path path = Paths.get(baseDirectory + containerName + "\\" + fileName);
			Files.delete(path);
		}
		catch (Exception e)
		{
			throw new ServiceException(e);
		}
	}
	
	@Override
	public boolean fileExists(String containerName, String fileName)
	{
		if(!isValidContainerName(containerName))
			throw new IllegalArgumentException("Invalid container name");
		
		if(!isValidFileName(fileName))
			throw new IllegalArgumentException("Invalid file name");
		
		try
		{
			Path path = Paths.get(baseDirectory + containerName + "\\" + fileName);
			return Files.exists(path);
		}
		catch (Exception e)
		{
			throw new ServiceException(e);
		}
	}
	
	@Override
	public byte[] getFileContent(String containerName, String fileName)
	{
		if(!isValidContainerName(containerName))
			throw new IllegalArgumentException("Invalid container name");
		
		if(!isValidFileName(fileName))
			throw new IllegalArgumentException("Invalid file name");
		
		try
		{
			Path path = Paths.get(baseDirectory + containerName + "\\" + fileName);
			return Files.readAllBytes(path);
		}
		catch (Exception e)
		{
			throw new ServiceException(e);
		}
	}

	@Override
	public String getFileContentType(String containerName, String fileName)
	{
		if(!isValidContainerName(containerName))
			throw new IllegalArgumentException("Invalid container name");
		
		if(!isValidFileName(fileName))
			throw new IllegalArgumentException("Invalid file name");
		
		try
		{
			Path path = Paths.get(baseDirectory + containerName + "\\" + fileName);
			return Files.probeContentType(path);
		}
		catch (Exception e)
		{
			throw new ServiceException(e);
		}
	}
	
	@Override
	public Set<String> listContainers()
	{
		try
		{
			File file = new File(baseDirectory);
			String[] directories = file.list(
					new FilenameFilter()
					{
						@Override
						public boolean accept(File dir, String name)
						{
							return dir.isDirectory();
						}
					});
			
			return new HashSet<String>(Arrays.asList(directories));
		}
		catch (Exception e)
		{
			throw new ServiceException(e);
		}
	}
	
	@Override
	public Set<String> listFiles(String containerName)
	{
		if(!isValidContainerName(containerName))
			throw new IllegalArgumentException("Invalid container name");
		
		try
		{
			File file = new File(baseDirectory + containerName);
			
			String[] files = file.list(
					new FilenameFilter()
					{
						@Override
						public boolean accept(File dir, String name)
						{
							return dir.isDirectory();
						}
					});
			
			return new HashSet<String>(Arrays.asList(files));
		}
		catch (Exception e)
		{
			throw new ServiceException(e);
		}
	}

	@Override
	public void saveFile(String containerName, String fileName, byte[] fileContent)
	{
		saveFile(containerName, fileName, fileContent, "application/octet-stream");
	}
	
	@Override
	public void saveFile(String containerName, String fileName, byte[] fileContent, String contentType)
	{
		if(!isValidContainerName(containerName))
			throw new IllegalArgumentException("Invalid container name");
		
		if(!isValidFileName(fileName))
			throw new IllegalArgumentException("Invalid file name");
		
		if(fileContent == null)
			throw new IllegalArgumentException("Invalid file content");
		
		if(contentType == null || contentType.equals("") || !contentType.contains("/"))
			throw new IllegalArgumentException("Invalid content type");
		
		try
		{
			Path path = Paths.get(baseDirectory + containerName + "\\" + fileName);
			Files.write(path, fileContent);
		}
		catch (Exception e)
		{
			throw new ServiceException(e);
		}
	}
	
	@Override
	public boolean isValidContainerName(String containerName)
	{
		if (containerName == null || containerName.isEmpty())
            return false;
		
		return true;
	}
    
	@Override
	public boolean isValidFileName(String fileNname)
	{
		if (fileNname == null || fileNname.isEmpty())
			return false;
		
		return true;
	}
}
